package com.yeook.ymax.ui.activitys;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.concurrent.TimeoutException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.yeook.ymax.R;
import com.yeook.ymax.db.DbStructure;
import com.yeook.ymax.service.MainService;
import com.yeook.ymax.service.MainService.LocalBinder;

public class SplashActivity extends Activity {

	private TextView mVersionNameText;
	private static final int SHOW_TIME_MIN = 800;
	private HashMap<String, String> updateParams = new HashMap<String, String>();
	private String LATEST_VERSION_CODE_URI = "http://www.yeook.com/webservices/wallpaper_latest_version.xml";
	private static final String TMP_UPDATE_FILE = Environment
			.getExternalStorageDirectory().getPath() + "/.y-max/ymaxUpdate.apk";
	public Context mContext;
	private final String SDCARD = Environment.getExternalStorageDirectory().getPath();
	private String LOCAL_PATH = SDCARD + "/.y-max";
	
	public boolean isUpdate = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splash);
		mContext = this;
		mVersionNameText = (TextView) findViewById(R.id.version_name);

		try {
			PackageManager manager = this.getPackageManager();
			PackageInfo info;
			info = manager.getPackageInfo(this.getPackageName(), 0);
			String version = info.versionName;

			mVersionNameText.setText(version);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		File file = new File(LOCAL_PATH);
		if (!file.exists()) {
			file.mkdirs();
		}

		new AsyncTask<Void, Void, Integer>() {

			@Override
			protected Integer doInBackground(Void... params) {
				int result = 0;
				long startTime = System.currentTimeMillis();
				result = checkVersion();
				long loadingTime = System.currentTimeMillis() - startTime;
				if (loadingTime < SHOW_TIME_MIN) {
					try {
						Thread.sleep(SHOW_TIME_MIN - loadingTime);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				return result;
			}

			@Override
			protected void onPostExecute(Integer result) {
				
				if(!isUpdate)
				{
					SharedPreferences myPrefs = PreferenceManager
							.getDefaultSharedPreferences(mContext);
					//第一次启动系统，初始化环境
					if(myPrefs.getBoolean("copy_db", true))
					{
						
						DbStructure dbhandler = new DbStructure(mContext);
						try {
							dbhandler.createDataBase();
						} catch (Exception e) {
							Log.e("YAX", e.getMessage(), e);
						}
						
						SharedPreferences.Editor editor = myPrefs.edit();
						editor.putBoolean("copy_db", false);
						editor.commit();
					}
					
					startMainActivity();
				}

			};
		}.execute(new Void[] {});

	}
	
	private void startMainPage(String page)
	{
		// ... ...
		Intent intent = new Intent();
		if("wallaper".equals(page)){
			intent.setClassName(SplashActivity.this,ResponsiveUIActivity.class.getName());
		}else{
			intent.setClassName(SplashActivity.this,RingtoneUIActivity.class.getName());
		}
		startActivity(intent);
		finish();
		int version = Integer.valueOf(android.os.Build.VERSION.SDK);
		if (version >= 5) {
			// 两个参数分别表示进入的动画,退出的动画
			overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
		}
	}
	
	public void startMainActivity()
	{
		SharedPreferences sPref = PreferenceManager
				.getDefaultSharedPreferences(this);
		
		String startPage = sPref.getString("start_page", "nothing");
		
		if("nothing".equals(startPage))
		{
			new AlertDialog.Builder(SplashActivity.this)  
			 .setTitle(R.string.start_page)  
			 .setItems(R.array.item_start_page_dialog, new DialogInterface.OnClickListener() {  
			         @Override  
			          public void onClick(DialogInterface dialog, final int which) {  
			        	 Editor pref = PreferenceManager
			     				.getDefaultSharedPreferences(SplashActivity.this).edit();
			        	 
			        	 String start_page = "wallaper";
		                  if(which == 0)
		                  {
		                	  pref.putString("start_page", "wallaper");
		                	  start_page = "wallaper";
		                  }
		                  else{
		                	  pref.putString("start_page", "ringtone");
		                	  start_page = "ringtone";
		                  }
		                  
		                  pref.commit();
		                  startMainPage(start_page);
		             }  
			}).show();  
		}
		else
		{
			startMainPage(startPage);
		}
		
	}
	
	public int checkVersion()
	{
		try {
			getUpdateParameters();
			if (getPackageManager().getPackageInfo(getPackageName(), 0).versionCode < Integer.parseInt(updateParams.get("versionCode"))) {
				isUpdate = true;
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						requestUpdateSelf();
					}
				});
				return 1;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	private void getUpdateParameters() {
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();

			URLConnection url = new URL(LATEST_VERSION_CODE_URI)
					.openConnection();
			url.setReadTimeout(3000);
			url.setConnectTimeout(3000);

			InputStream a = new BufferedInputStream(url.getInputStream());
			Document dom = builder.parse(new InputSource(a));
			dom.getDocumentElement().normalize();

			NodeList items = dom.getElementsByTagName("versionCode");
			if (items.getLength() > 0) {
				Node item = items.item(0);
				Log.d("Y-Max-XmlElement Name", item.getNodeName());
				Log.d("Y-Max-XmlElement Value", item.getFirstChild()
						.getNodeValue().trim());
				updateParams.put("versionCode", item.getFirstChild()
						.getNodeValue().trim());
			}

			items = dom.getElementsByTagName("uri");
			if (items.getLength() > 0) {
				Node item = items.item(0);
				Log.d("Y-Max-XmlElement Name", item.getNodeName());
				Log.d("Y-Max-XmlElement Value", item.getFirstChild()
						.getNodeValue().trim());
				updateParams.put("uri", item.getFirstChild().getNodeValue()
						.trim());
			}

			items = dom.getElementsByTagName("md5");
			if (items.getLength() > 0) {
				Node item = items.item(0);
				Log.d("Y-Max-XmlElement Name", item.getNodeName());
				Log.d("Y-Max-XmlElement Value", item.getFirstChild()
						.getNodeValue().trim());
				updateParams.put("md5", item.getFirstChild().getNodeValue()
						.trim());
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void requestUpdateSelf() {
		View simpleView = LayoutInflater.from(mContext).inflate(
				R.layout.dialog_simple_layout, null);
		Builder dialogBuilder = new AlertDialog.Builder(mContext)
				.setView(simpleView);
		final AlertDialog updateSelfDialog = dialogBuilder.create();
		updateSelfDialog.setTitle(getText(R.string.update_self_title));
		updateSelfDialog.setIcon(R.drawable.ic_launcher);
		TextView message = (TextView) simpleView
				.findViewById(R.id.dialog_message);
		message.setText(R.string.update_self_msg);
		updateSelfDialog.setCancelable(false);
		updateSelfDialog.setButton(Dialog.BUTTON_POSITIVE,
				getString(android.R.string.yes), new Dialog.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						new DownloadSelfUpdate().execute();
						//startMainActivity();
					}
				});
		updateSelfDialog.setButton(Dialog.BUTTON_NEGATIVE,
				getString(android.R.string.no), new Dialog.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int arg1) {
						dialog.dismiss();
						startMainActivity();
					}
				});
		updateSelfDialog.show();

	}

	private class DownloadSelfUpdate extends AsyncTask<Void, Void, Void> {
		private final ProgressDialog dialog = new ProgressDialog(mContext);

		String latestVersionUri;
		String referenceMd5;

		void retrieveUpdateParameters() {
			try {
				latestVersionUri = updateParams.get("uri");
				referenceMd5 = updateParams.get("md5");
			} catch (Exception e) {
				e.printStackTrace();
				Log.d("Y-Max-Auto-Update",
						"Update connection failed!  Keeping current version.");
			}
		}

		@Override
		protected void onPreExecute() {
			this.dialog.setMessage(getString(R.string.retrieving_update));
			this.dialog.setIndeterminate(true);
			this.dialog.setCancelable(false);
			this.dialog.show();
			super.onPreExecute();
			retrieveUpdateParameters();
		}

		@Override
		protected Void doInBackground(Void... paramArrayOfParams) {
			try {
				if (latestVersionUri == null) {
					retrieveUpdateParameters();
				}
				
				File f_chk = new File(TMP_UPDATE_FILE);
				if (f_chk.exists()) {
					f_chk.delete();
				}
				f_chk = null;

				FileOutputStream saveit = new FileOutputStream(TMP_UPDATE_FILE);
				DefaultHttpClient mHttpClient = new DefaultHttpClient();
				HttpGet mHttpGet = new HttpGet(latestVersionUri);

				HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);

				if (mHttpResponse == null) {
					Log.d("Y-Max", "Problem in network... retry...");
					mHttpResponse = mHttpClient.execute(mHttpGet);
					if (mHttpResponse == null) {
						Log.d("Y-Max", "Major network exception... Exiting!");
						/*
						 * msg_al.arg1= 1;
						 * download_error_handler.sendMessage(msg_al);
						 */
						saveit.close();
						throw new TimeoutException();
					}
				}

				if (mHttpResponse.getStatusLine().getStatusCode() == 401) {
					saveit.close();
					throw new TimeoutException();
				} else {
					InputStream getit = mHttpResponse.getEntity().getContent();
					byte data[] = new byte[8096];
					int bytesRead;
					bytesRead = getit.read(data, 0, 8096);
					while (bytesRead != -1) {
						// download_tick.sendEmptyMessage(readed);
						saveit.write(data, 0, bytesRead);
						bytesRead = getit.read(data, 0, 8096);
					}
					Log.d("Y-Max", "Download done!");
					saveit.flush();
					saveit.close();
					getit.close();
				}
			} catch (Exception e) {
				// download_error_handler.sendMessage(msg_al);
				e.printStackTrace();
				Log.d("Y-Max-Auto-Update",
						"Update connection failed!  Keeping current version.");
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {

			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
			}
			super.onPostExecute(result);

			try {
				doUpdateSelf();
			} catch (Exception e) {
				e.printStackTrace();
				Log.d("Y-Max-Auto-Update",
						"Update package checksum failed!  Keeping current version.");
				if (this.dialog.isShowing()) {
					this.dialog.dismiss();
				}
				finish();
				super.onPostExecute(result);
			}

		}
	}

	private void doUpdateSelf() {
		Intent intent = new Intent();
		intent.setAction(android.content.Intent.ACTION_VIEW);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setDataAndType(Uri.parse("file://" + TMP_UPDATE_FILE),
				"application/vnd.android.package-archive");
		startActivityForResult(intent, 99);
	}

}